//
//  WmcTeamCloudAlbumMembersVM.swift
//  YPWatermarkCamera
//
//  Created by 赵洋 on 2022/9/8.
//

import RxRelay
import UIKit

class WmcTeamCloudAlbumMembersVM: WmcBaseVM {
    /// 成员列表
    let members: BehaviorRelay<[WmcTeamMemberModel]> = .init(value: [])
    let error: BehaviorRelay<Error?> = .init(value: nil)
    /// 备份搜索数据源
    var searchMembers: [WmcTeamMemberModel] = .init()
    /// 相册
    var teamAblum: WmcMediaTeamAlbumModel?
    // 自己
    let selfMemeber: BehaviorRelay<WmcTeamMemberModel?> = .init(value: nil)
    // 自己
    var mySelf: WmcTeamMemberModel?

    /// 获取团队成员
    /// - Returns: description
    func getTeamMemberList() {
        guard let teamId = teamAblum?.teamId else {
            return
        }
        WmcHudManager.loading()
        WmcMediaTeamManagerAPI.fetchMemberList(id: teamId).subscribe { [weak self] list in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            weakSelf.members.accept(list)
            weakSelf.searchMembers.removeAll()
            weakSelf.searchMembers.append(contentsOf: list)
            self?.getSelfMemeber(list: list)
        } onError: { [weak self] error in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
            weakSelf.error.accept(error)
        }.disposed(by: rx.disposeBag)
    }

    /// 本地搜索成员
    /// - Parameter searchStr: 搜索关键字
    /// - Returns: description
    func searchMembers(searchStr: String?) {
        guard let searchStr = searchStr else {
            return
        }
        if searchStr.count == 0 {
            members.accept(searchMembers)
        } else {
            let filtered = searchMembers.filter { ($0.showName).contains(searchStr) }
            members.accept(filtered)
        }
    }

    private func getSelfMemeber(list: [WmcTeamMemberModel]) {
        list.forEach { member in
            if member.isSelf() {
                self.selfMemeber.accept(member)
                self.mySelf = member
            }
        }
    }
}
